import Router from 'koa-router';
import { PassThrough } from 'stream';
import { generate } from '../utils/index.js';
const chat = new Router();

chat.post('/', async(ctx) => {
    ctx.set({
        'Connection': 'keep-alive',
        'Cache-Control': 'no-cache',
        'Content-Type': 'text/event-stream',
    });
    const stream = new PassThrough();
    ctx.body = stream;
    ctx.status = 200;
    const data = ctx.request.body
    const history = []
    for(let i = 0; i < data.message.length; i++){
        history.push({
            role: (()=>{
                switch (data.is_bots[i]){
                    case 1:
                        return 'ai'
                    case 0:
                        return 'me'
                }
            })(),
            message: data.message[i]
        })
    }
    generate(data.text, history, (e) => {
        stream.write(JSON.stringify(e))
    }, () => {
        stream.end()
    })
})
export default chat;
